package com.heo.music.player.config.swagger;

import com.fasterxml.classmate.TypeResolver;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import springfox.documentation.OperationNameGenerator;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.OperationBuilderPlugin;
import springfox.documentation.spi.service.contexts.OperationContext;
import springfox.documentation.swagger.common.SwaggerPluginSupport;

/**
 * created on 2023-12-22 15:03
 *
 * @author 星天无极
 **/
@Component
@Slf4j
@ConditionalOnProperty(
    name = {"knife4j.enable"},
    havingValue = "true"
)
@RequiredArgsConstructor
public class CustomOperationBuilderPlugin implements OperationBuilderPlugin {

    private final TypeResolver typeResolver;

    private final OperationNameGenerator nameGenerator;

    @Override
    public void apply(OperationContext context) {
        if (context.httpMethod() == HttpMethod.HEAD &&
            context.getReturnType().equals(typeResolver.resolve(ResponseEntity.class, byte[].class))
        ) {
            context.operationBuilder().codegenMethodNameStem(context.getName() + "Head");
        } else {
            context.operationBuilder().codegenMethodNameStem(context.getName());
        }

    }

    @Override
    public boolean supports(@NonNull DocumentationType documentationType) {
        return SwaggerPluginSupport.pluginDoesApply(documentationType);
    }
}
